// import app_upgrade from '@/uni_modules/app-upgrade/js_sdk/index.js'
import { BASE_URL } from '@/common/config'

const utils = {
  // onUpdate() {
  //   app_upgrade(async (versionCode) => {
  //     let [error, res] = await uni.request({
  //       url: BASE_URL + '/api/public/android-latest-version',
  //       method: 'GET'
  //     })
  //     if (res.statusCode == 200) {
  //       if (res.data.code == 0) {
  //         let json = res.data.data
  //         let apkNum = Number(json.no)
  //         let version = plus.runtime.versionCode
  //         if (apkNum > version) {
  //           return {
  //             changelog: json.content,
  //             status: 1,
  //             path: json.apk_format
  //           }
  //         } else {
  //           return {
  //             changelog: json.content,
  //             status: 0,
  //             path: json.apk_format
  //           }
  //         }
  //       }
  //     }
  //   }, 1)
  // },
  tips(str, duration) {
    let showtime = uni.getStorageSync('toast_show_time')
    let thisTime = new Date().getTime()
    if (thisTime - showtime > 500) {
      uni.showToast({
        title: str,
        icon: 'none',
        duration: duration ? duration : 1500
      })
    }
    uni.setStorageSync('toast_show_time', thisTime)
  },
  isLogin() {
    return uni.getStorageSync('tokenInfo') && uni.getStorageSync('userInfo')
  },
  loginToBack() {
    const backUrl = uni.getStorageSync('backUrl')
    setTimeout(() => {
      uni.removeStorageSync('backUrl')
      if (backUrl) {
        uni.redirectTo({
          url: backUrl
        })
      } else {
        uni.reLaunch({
          url: '/pages/ucenter/ucenter'
        })
      }
    }, 800)
  },
  handleLogout(callback = null) {
    const app = this
    uni.showModal({
      title: '友情提示',
      content: '您确定要退出登录吗?',
      success: (res) => {
        if (!res.confirm) {
          return
        }
        uni.removeStorageSync('tokenInfo')
        uni.removeStorageSync('userInfo')
        uni.removeStorageSync('saleMemberNo')
        if (callback && typeof callback === 'function') {
          callback()
        } else {
          app.goToLogin()
        }
      }
    })
  },
  goToLogin(backUrl = '') {
    if (backUrl && backUrl.length > 0) {
      uni.setStorageSync('backUrl', backUrl)
    }
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1].route || pages[pages.length - 1].$vm.$mp.page.route
    // #ifndef MP-WEIXIN
    if (currentPage != '/universal/login/login') {
      uni.redirectTo({
        url: '/universal/login/login',
        fail: (e) => {
          console.log('===', e)
        }
      })
    }
    // #endif
    // #ifdef MP-WEIXIN
    if (currentPage != 'other/wx-login/wx-login') {
      uni.redirectTo({
        url: '/other/wx-login/wx-login',
        fail: (e) => {
          console.log('===', e)
        }
      })
    }
    // #endif
  },
  checkLogin(redirect = false, backUrl = '') {
    const userInfo = uni.getStorageSync('userInfo')
    //console.log("userInfo", userInfo)
    if (!userInfo || Number(userInfo.id) === 0) {
      if (!redirect) {
        return false
      }
      const delay = 1500
      uni.showToast({
        title: '未登录或登录过期，请先登录',
        icon: 'none',
        duration: delay
      })
      setTimeout(() => {
        this.goToLogin(backUrl)
      }, delay)
      return false
    }
    return true
  },
  goToHome() {
    uni.switchTab({
      url: '/pages/index/index'
    })
  },
  goToUserCenter() {
    uni.reLaunch({
      url: '/pages/ucenter/ucenter'
    })
  },
  judgeType(obj) {
    // tostring会返回对应不同的标签的构造函数
    const toString = Object.prototype.toString
    const map = {
      '[object Boolean]': 'boolean',
      '[object Number]': 'number',
      '[object String]': 'string',
      '[object Function]': 'function',
      '[object Array]': 'array',
      '[object Date]': 'date',
      '[object RegExp]': 'regExp',
      '[object Undefined]': 'undefined',
      '[object Null]': 'null',
      '[object Object]': 'object'
    }
    // 检查当前环境是否为小程序
    const isMiniProgram = typeof wx !== 'undefined' // 根据你的具体小程序环境进行调整
    // 在小程序中，可以跳过对 Element 的检查
    if (!isMiniProgram && obj instanceof Element) {
      return 'element'
    }
    return map[toString.call(obj)]
  },
  deepClone(data) {
    const type = this.judgeType(data)
    let obj
    if (type === 'array') {
      obj = []
    } else if (type === 'object') {
      obj = {}
    } else {
      // 不再具有下一层次
      return data
    }
    if (type === 'array') {
      for (let i = 0, len = data.length; i < len; i++) {
        obj.push(this.deepClone(data[i]))
      }
    } else if (type === 'object') {
      // 对原型上的方法也拷贝了....
      for (const key in data) {
        obj[key] = this.deepClone(data[key])
      }
    }
    return obj
  },
  route(params, isLogin) {
    if (isLogin) {
      if (uni.getStorageSync('tokenInfo')) {
        uni.$u.route(params)
        return
      }
      if (this.isObject(params)) {
        this.goToLogin(params.url + '?' + this.urlEncode(params.params))
        return
      }
      this.goToLogin(params)
      return
    }
    uni.$u.route(params)
  },
  urlEncode(obj = {}) {
    const result = []
    for (const key in obj) {
      const item = obj[key]
      if (!item) {
        continue
      }
      if (this.isArray(item)) {
        item.forEach((val) => {
          result.push(key + '=' + val)
        })
      } else {
        result.push(key + '=' + item)
      }
    }
    return result.join('&')
  },
  isEmpty(value) {
    if (this.isArray(value)) {
      return value.length === 0
    }
    if (this.isObject(value)) {
      return Object.keys(value).length === 0
    }
    return !value
  },
  isArray(array) {
    return Object.prototype.toString.call(array) === '[object Array]'
  },
  isObject(object) {
    return Object.prototype.toString.call(object) === '[object Object]'
  },
  parseTime(time, pattern = '{y}-{m}-{d} {h}:{i}:{s}') {
    if (arguments.length === 0 || !time) {
      return null
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
      date = time
    } else {
      if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
        time = parseInt(time)
      } else if (typeof time === 'string') {
        time = time
          .replace(new RegExp(/-/gm), '/')
          .replace('T', ' ')
          .replace(new RegExp(/\.[\d]{3}/gm), '')
      }
      if (typeof time === 'number' && time.toString().length === 10) {
        time = time * 1000
      }
      date = new Date(time)
    }
    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      let value = formatObj[key]
      // Note: getDay() returns 0 on Sunday
      if (key === 'a') {
        return ['日', '一', '二', '三', '四', '五', '六'][value]
      }
      if (result.length > 0 && value < 10) {
        value = '0' + value
      }
      return value || 0
    })
    return time_str
  }
}

export default utils
